package com.v2future.sjt.collegecheckingattendance.home;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.event.EventFragment;
import com.v2future.sjt.collegecheckingattendance.event.ReleaseEventActivity;
import com.v2future.sjt.collegecheckingattendance.fruit.AddFruitActivity;
import com.v2future.sjt.collegecheckingattendance.fruit.FruitFragment;
import com.v2future.sjt.collegecheckingattendance.home.adapter.MyFragmentPagerAdapter;
import com.v2future.sjt.collegecheckingattendance.home.bean.LoginResultBean;
import com.v2future.sjt.collegecheckingattendance.home.bean.TermBean;
import com.v2future.sjt.collegecheckingattendance.leave.LeaveFragment;
import com.v2future.sjt.collegecheckingattendance.message.MessageFragment;
import com.v2future.sjt.collegecheckingattendance.personal.PersonalFragment;
import com.v2future.sjt.collegecheckingattendance.rollcall.RollCallFragment;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.MyRadioButton;
import com.v2future.sjt.collegecheckingattendance.widget.MyViewPager;
import com.v2future.sjt.collegecheckingattendance.widget.view.PullToRefreshView;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by sjt on 16/1/2.
 * 首页
 */
public class HomeActivity extends MainActivity implements PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener{

    FragmentTransaction fragmentTransaction;

    MyViewPager homePager;
    ArrayList<Fragment> fragments;
    ArrayList<RadioButton> radioButtons;

    RadioGroup nativeRg;
    MyRadioButton eventRb, leaveRb, fruitRb, personalRb;
    EventFragment eventFragment;
    PersonalFragment personalFragment;
    LeaveFragment leaveFragment;
    RollCallFragment rollCallFragment;
    FruitFragment fruitFragment;
    MessageFragment messageFragment;

    LoginResultBean mLoginResultBean;

    public static boolean isForeground = false;


    public static final int STUDENT = 2;
    public static final int TEACHER = 1;

    //用来接受onNewIntent
    public static final int FLAG_EVENT = 101;
    public static final int FLAG_LEAVE = 102;
    public static final int FLAG_FRUIT = 103;
    public static final int FLAG_PERSONAL = 104;
    public static final int FLAG_ROLLCALL = 105;
    public static final int FLAG_MESSAGE = 106;

    /**
     * 用户身份
     */
    public int userIdentity = STUDENT;

    /**
     * 传递的tag
     */
    public static final String INTENT_TAG_REFRESH = "tag_refresh";//刷新数据

    /**
     * the layout use loading fragment
     */
    RelativeLayout mainLayout;

    @Override
    public void init() {
//        Constants.isOpenForPush = true;
        fragments = new ArrayList<Fragment>();
        radioButtons = new ArrayList<RadioButton>();
        mLoginResultBean = getUserInfo();
        if (null != mLoginResultBean && !TextUtils.isEmpty(mLoginResultBean.getData().getSourceTypeId())) {
            userIdentity = Integer.parseInt(mLoginResultBean.getData().getSourceTypeId());
        }
        else {
            tip("用户身份格式有误");
        }
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_home);
        setTitleText(R.string.event);
        nativeRg = (RadioGroup) findViewById(R.id.rg_native);
        homePager = (MyViewPager) findViewById(R.id.vp_home);
        eventRb = (MyRadioButton) findViewById(R.id.rb_event);
        radioButtons.add(eventRb);
        leaveRb = (MyRadioButton) findViewById(R.id.rb_leave);
        radioButtons.add(leaveRb);
        fruitRb = (MyRadioButton) findViewById(R.id.rb_fruit);
        radioButtons.add(fruitRb);
        personalRb = (MyRadioButton) findViewById(R.id.rb_personal);
        radioButtons.add(personalRb);
    }

    @Override
    public void initAfter() {
        //获取学期
        doGetTerm();
        if (userIdentity == STUDENT) {
            leaveRb.setText(R.string.leave);
            fruitRb.setText(R.string.fruit);
        }
        else if (userIdentity == TEACHER) {
            leaveRb.setText(R.string.roll_call);
            fruitRb.setText(R.string.message);
        }
        eventFragment = new EventFragment();
        fragments.add(eventFragment);
        if (userIdentity == TEACHER) {
            rollCallFragment = new RollCallFragment();
            fragments.add(rollCallFragment);
            messageFragment = new MessageFragment();
            fragments.add(messageFragment);
        }
        else {
            leaveFragment = new LeaveFragment();
            fragments.add(leaveFragment);
            fruitFragment = new FruitFragment();
            fragments.add(fruitFragment);
        }
        personalFragment = new PersonalFragment();
        fragments.add(personalFragment);
        //默认活动页面显示发布按钮
//        showRightView(getString(R.string.release), releaseListener);
        //给ViewPager设置适配器
        homePager.setOffscreenPageLimit(4);
        homePager.setAdapter(new MyFragmentPagerAdapter(fragmentManager, fragments));
        homePager.setCurrentItem(0);//设置当前显示标签页为第一页
        homePager.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器
        nativeRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                homePager.setTouchIntercept(true);
                hideReleaseView();
                switch (checkedId) {
                    case R.id.rb_event:
                        homePager.setCurrentItem(0);
//                        showRightView(getString(R.string.release), releaseListener);
                        break;
                    case R.id.rb_leave:
                        homePager.setCurrentItem(1);
                        break;
                    case R.id.rb_fruit:
                        homePager.setCurrentItem(2);
                        if (userIdentity == TEACHER) {
                            homePager.setTouchIntercept(false);
                        }
                        break;
                    case R.id.rb_personal:
                        homePager.setCurrentItem(3);
                        break;
                    default:
                        break;
                }
            }
        });
        setPushTags(getUserInfo());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch (intent.getIntExtra("id", 0)){
            case FLAG_EVENT:
                eventFragment.onNewIntent(intent);
                break;
            case FLAG_LEAVE:

                break;
            case FLAG_MESSAGE:

                break;
            case FLAG_ROLLCALL:
                rollCallFragment.onNewIntent(intent);
                break;
            case FLAG_FRUIT:

                break;
            case FLAG_PERSONAL:

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Constants.IMAGE_CODE){
            if(resultCode == RESULT_OK){
                // Get the result list of select image paths
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                personalFragment.setHead(path);
            }
        }
    }

    protected void showRightView(String name, View.OnClickListener listener){
        setRightText(name, listener);
    }

    protected void hideReleaseView(){
        hideRightText();
    }

    /**
     * get term
     */
    private void doGetTerm(){
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.GET_TERM));
        NetUtils.doGetRequest(this, params, new NetTaskListener<TermBean>() {

            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(TermBean result) {
                //保存term到本地内存
                getBaseApplication().insertCathe(Constants.CACHE_KEY_TERM, result);
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(TermBean result) {

            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {

            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(TermBean result) {

            }
        });
    }

    /**
     * 发布点击事件
     */
    private View.OnClickListener releaseListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(HomeActivity.this, ReleaseEventActivity.class);
            startActivity(intent);
        }
    };

    private View.OnClickListener addListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(HomeActivity.this, AddFruitActivity.class);
            startActivity(intent);
        }
    };

    @Override
    public void onFooterRefresh(PullToRefreshView view) {

    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {

    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
            homePager.setTouchIntercept(true);
            hideReleaseView();
            switch (i) {
                case 0:
                    nativeRg.check(R.id.rb_event);
                    setTitleText(getString(R.string.event));
//                    showRightView(getString(R.string.release), releaseListener);
                    break;
                case 1:
                    nativeRg.check(R.id.rb_leave);
                    if (userIdentity == TEACHER) {
                        setTitleText(getString(R.string.roll_call));
                    }
                    else {
                        setTitleText(getString(R.string.leave));
                    }
                    break;
                case 2:
                    nativeRg.check(R.id.rb_fruit);
                    if (userIdentity == TEACHER) {
                        setTitleText(getString(R.string.message));
                        homePager.setTouchIntercept(false);
                    }
                    else {
                        setTitleText(getString(R.string.fruit));
                    }
                    break;
                case 3:
                    nativeRg.check(R.id.rb_personal);
                    setTitleText(getString(R.string.personal));
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    }

    /** The exit time. */
    private long exitTime = 0;

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#dispatchKeyEvent(android.view.KeyEvent)
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                tip("再按一次退出");

                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}
